package com.example.baserecyclerviewadapterdemo.activity;

import android.os.Bundle;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.baserecyclerviewadapterdemo.R;
import com.example.baserecyclerviewadapterdemo.fragment.AdapterUseFragment;
import com.example.baserecyclerviewadapterdemo.fragment.BaseUseFragment;
import com.example.baserecyclerviewadapterdemo.fragment.FuncUseFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

    private enum TabFragment{
        baseUse(R.id.item_base, BaseUseFragment.class),
        adapterUse(R.id.item_adapter, AdapterUseFragment.class),
        funcUse(R.id.item_func, FuncUseFragment.class);

        private Fragment fragment;
        private final int menuId;
        private final Class<? extends Fragment> clazz;

        TabFragment(@IdRes int menuId,Class<? extends Fragment> clazz){
            this.menuId = menuId;
            this.clazz = clazz;
        }

        @NonNull
        public Fragment fragment(){
            if (fragment == null) {
                try {
                    fragment = clazz.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                    fragment = new Fragment();
                }
            }
            return fragment;
        }

        public static TabFragment from(int menuId){
            for (TabFragment fragment : TabFragment.values()) {
                if (fragment.menuId == menuId) {
                    return fragment;
                }
            }
            return baseUse;
        }

        public static void onDestroy(){
            for (TabFragment value : TabFragment.values()) {
                value.fragment = null;
            }
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BottomNavigationView navigation = findViewById(R.id.navigation);

        ViewPager viewPager = findViewById(R.id.content);
        viewPager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return TabFragment.values()[position].fragment();
            }

            @Override
            public int getCount() {
                return TabFragment.values().length;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TabFragment.onDestroy();
    }
}
